package cn.cheegon.blog.service.impl;

import cn.cheegon.blog.common.api.CommonPage;
import cn.cheegon.blog.common.exception.Asserts;
import cn.cheegon.blog.common.security.jwt.JwtTokenUtil;
import cn.cheegon.blog.common.security.entity.AdminUserDetails;
import cn.cheegon.blog.entity.req.RegisterReq;
import cn.cheegon.blog.entity.req.ResetPasswordReq;
import cn.cheegon.blog.entity.req.UpdatePasswordReq;
import cn.cheegon.blog.entity.rsp.LoginRsp;
import cn.cheegon.blog.entity.rsp.UserInfoRsp;
import cn.cheegon.blog.mapper.UmsAdminMapper;
import cn.cheegon.blog.model.UmsAdmin;
import cn.cheegon.blog.service.UmsAdminService;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author cheegon
 * @since 2024-06-12
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UmsAdminMapper umsAdminMapper;

    /**
     * 注册功能
     *
     * @return
     */
    @Override
    public LoginRsp register(RegisterReq req) {
        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", req.getUsername());
        List<UmsAdmin> umsAdmins = umsAdminMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(umsAdmins)) {
            Asserts.fail("用户名已经存在");
        }
        UmsAdmin umsAdmin = new UmsAdmin();
        BeanUtils.copyProperties(req, umsAdmin);
        umsAdmin.setStatus(1);
        if (umsAdmin.getAvatar() == null || umsAdmin.getAvatar().isEmpty()) {
            umsAdmin.setAvatar("http://47.100.123.137/images/ic_avatar.jpg");
        }
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
        umsAdminMapper.insert(umsAdmin);
        AdminUserDetails userDetails = new AdminUserDetails(umsAdmin, new ArrayList<>());
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginRsp rsp = new LoginRsp();
        rsp.setToken(jwtTokenUtil.sign(userDetails));
        UserInfoRsp user = new UserInfoRsp();
        BeanUtils.copyProperties(umsAdmin, user);
        rsp.setUser(user);
        return rsp;
    }

    /**
     * 登录功能
     *
     * @param username 用户名
     * @param password 密码
     * @return 生成的JWT的token
     */
    @Override
    public LoginRsp login(String username, String password) {
        LoginRsp rsp = new LoginRsp();
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                Asserts.fail("用户名或密码错误");
            }
            if (!userDetails.isEnabled()) {
                Asserts.fail("帐号已被禁用");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            rsp.setToken(jwtTokenUtil.sign(userDetails));
            AdminUserDetails adminUserDetails = (AdminUserDetails) userDetails;
            UserInfoRsp user = new UserInfoRsp();
            BeanUtils.copyProperties(adminUserDetails.getUmsAdmin(), user);
            rsp.setUser(user);
            UmsAdmin umsAdmin = new UmsAdmin();
            umsAdmin.setId(adminUserDetails.getUmsAdmin().getId());
            umsAdmin.setLastLoginTime(LocalDateTimeUtil.now());
            umsAdminMapper.updateById(umsAdmin);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
            Asserts.fail("用户名或密码错误");
        }
        return rsp;
    }

    /**
     * 用户列表
     *
     * @return
     */
    @Override
    public CommonPage<UserInfoRsp> list(int pageNum, int pageSize) {
        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();
        Page<UmsAdmin> umsAdminPage = umsAdminMapper.selectPage(new Page<UmsAdmin>(pageNum, pageSize), queryWrapper);
        if (CollectionUtils.isEmpty(umsAdminPage.getRecords())) {
            return CommonPage.emptyPage(umsAdminPage);
        }
        return CommonPage.restPage(umsAdminPage, UserInfoRsp.class);
    }

    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        UmsAdmin admin = getAdminByUsername(username);
        if (admin != null) {
            return new AdminUserDetails(admin, new ArrayList<>());
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    /**
     * 根据用户名获取后台管理员
     *
     * @param username
     * @return
     */
    @Override
    public UmsAdmin getAdminByUsername(String username) {
        QueryWrapper<UmsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return umsAdminMapper.selectOne(queryWrapper);
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    @Override
    public UmsAdmin getCurrUser() {
        try {
            AdminUserDetails userDetails = (AdminUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return userDetails.getUmsAdmin();
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 根据用户id获取用户
     *
     * @param id
     * @return
     */
    @Override
    public UmsAdmin getUserById(Long id) {
        return umsAdminMapper.selectById(id);
    }

    /**
     * 根据用户id获取用户
     *
     * @param ids
     * @return
     */
    @Override
    public Map<Long, UmsAdmin> getUserByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new HashMap<>();
        }
        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids);
        List<UmsAdmin> list = umsAdminMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        Map<Long, UmsAdmin> map = list.stream().collect(Collectors.toMap(UmsAdmin::getId, admin -> admin));
        return map;
    }

    /**
     * 重置密码
     *
     * @return
     */
    @Override
    public void resetPassword(Long id, String pwd) {

    }

    /**
     * 修改密码
     *
     * @return
     */
    @Override
    public void updatePassword(Long id, String pwd, String newPwd) {
        UmsAdmin umsAdmin = this.baseMapper.selectById(id);
        if (!passwordEncoder.matches(pwd, umsAdmin.getPassword())) {
            Asserts.fail("当前密码错误");
        }
        umsAdmin.setPassword(passwordEncoder.encode(newPwd));
        this.baseMapper.updateById(umsAdmin);
    }

    /**
     * 修改指定用户信息
     *
     * @param admin
     */
    @Override
    public void update(UmsAdmin admin) {
        UmsAdmin currUser = getCurrUser();
        UmsAdmin umsAdmin = this.baseMapper.selectById(admin.getId());
        if (!Objects.equals(currUser.getId(), admin.getId())
                && (Objects.equals("2", umsAdmin.getType()))) {
            Asserts.fail("不能更改其他超管用户信息");
        }
        this.baseMapper.updateById(admin);
    }

    @Override
    public void changeType(Long id, Integer type) {
        UmsAdmin currUser = getCurrUser();
        if (Objects.equals(currUser.getId(), id)) {
            Asserts.fail("不能更改当前登录用户");
        }
        if (currUser.getType() == 2) {
            Asserts.fail("不能更改超级管理员");
        }
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setId(id);
        umsAdmin.setType(type);
        this.baseMapper.updateById(umsAdmin);
    }

    @Override
    public void changeStatus(Long id, Integer status) {
        UmsAdmin currUser = getCurrUser();
        if (Objects.equals(currUser.getId(), id)) {
            Asserts.fail("不能更改当前登录用户");
        }
        if (currUser.getType() == 2) {
            Asserts.fail("不能更改超级管理员");
        }
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setId(id);
        umsAdmin.setStatus(status);
        this.baseMapper.updateById(umsAdmin);
    }

    /**
     * 删除指定用户
     *
     * @param id
     * @return
     */
    @Override
    public void delete(Long id) {
        UmsAdmin currUser = getCurrUser();
        if (Objects.equals(currUser.getId(), id)) {
            Asserts.fail("不能删除当前登录用户");
        }
        if (currUser.getType() == 2) {
            Asserts.fail("不能删除超级管理员");
        }
        umsAdminMapper.deleteById(id);
    }
}
